<template>
  <el-dialog
    :title="$t('project.editTask')"
    v-model="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      v-loading="loading"
    >
      <!-- 任务标题 -->
      <el-form-item :label="$t('project.taskTitle')" prop="title">
        <el-input 
          v-model="form.title" 
          :placeholder="$t('project.taskTitlePlaceholder')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 任务描述 -->
      <el-form-item :label="$t('project.taskDescription')" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="4"
          :placeholder="$t('project.taskDescriptionPlaceholder')"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <!-- 任务优先级和分配者 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('project.priority.description')" prop="priority">
            <el-select 
              v-model="form.priority" 
              class="w-100"
              :placeholder="$t('project.priorityPlaceholder')"
            >
              <el-option
                v-for="priority in priorityOptions"
                :key="priority.value"
                :label="priority.label"
                :value="priority.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('project.assignee')" prop="assigneeId">
            <el-select 
              v-model="form.assigneeId" 
              class="w-100"
              :placeholder="$t('project.assigneePlaceholder')"
              filterable
              clearable
            >
              <el-option
                v-for="member in teamMembers"
                :key="member.userId"
                :label="member.username || member.nickname || `用户${member.userId}`"
                :value="member.userId"
              >
                <div class="member-option">
                  <el-avatar :size="24" :src="member.avatarUrl">
                    {{ (member.username || member.nickname || 'U')?.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <span>{{ member.username || member.nickname || `用户${member.userId}` }}</span>
                  <el-tag size="small" v-if="member.role === 'OWNER'">
                    {{ $t('team.role.owner') }}
                  </el-tag>
                  <el-tag size="small" v-else-if="member.role === 'ADMIN'">
                    {{ $t('team.role.admin') }}
                  </el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 截止日期和预估工时 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('project.dueDate')" prop="dueDate">
            <el-date-picker
              v-model="form.dueDate"
              type="datetime"
              :placeholder="$t('project.dueDatePlaceholder')"
              class="w-100"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('project.estimatedHours')" prop="estimatedHours">
            <el-input-number
              v-model="form.estimatedHours"
              :min="0"
              :max="999"
              :step="0.5"
              :precision="1"
              class="w-100"
              :placeholder="$t('project.estimatedHoursPlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 实际工时 -->
      <el-form-item :label="$t('project.actualHours')" prop="actualHours">
        <el-input-number
          v-model="form.actualHours"
          :min="0"
          :max="999"
          :step="0.5"
          :precision="1"
          class="w-100"
          :placeholder="$t('project.actualHoursPlaceholder')"
        />
      </el-form-item>

      <!-- 任务状态 -->
      <el-form-item :label="$t('project.taskStatus')" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio-button 
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.value"
          >
            {{ status.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!-- 完成时间（只读） -->
      <el-form-item 
        v-if="task?.completedAt" 
        :label="$t('project.completedAt')"
      >
        <el-input 
          :value="formatDateTime(task.completedAt)"
          readonly
          disabled
        />
      </el-form-item>

      <!-- 任务进度 -->
      <el-form-item :label="$t('project.taskProgress')">
        <div class="progress-container">
          <el-slider
            v-model="taskProgress"
            :min="0"
            :max="100"
            :step="5"
            :format-tooltip="value => `${value}%`"
            :marks="{
              0: '0%',
              25: '25%',
              50: '50%',
              75: '75%',
              100: '100%'
            }"
          />
          <div class="progress-info">
            <span>{{ taskProgress }}% {{ $t('project.completed') }}</span>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ $t('common.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { taskApi } from '@/api/project'
import type { Task, TaskUpdateRequest } from '@/types/project'
import { TaskPriority, TaskStatus } from '@/types/project'
import { formatDateTime } from '@/utils/date'

// Props
interface Props {
  modelValue: boolean
  task: Task | null
  teamMembers: Array<{
    userId: number
    username?: string
    nickname?: string
    avatarUrl?: string
    role: string
    status: string
  }>
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const { t } = useI18n()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const taskProgress = ref(0)
const form = ref<TaskUpdateRequest & { status: string }>({
  title: '',
  description: '',
  priority: TaskPriority.MEDIUM,
  assigneeId: undefined,
  dueDate: undefined,
  estimatedHours: undefined,
  actualHours: undefined,
  status: TaskStatus.TODO
})

// 计算属性
const priorityOptions = computed(() => [
  { value: TaskPriority.LOW, label: t('project.priority.low') },
  { value: TaskPriority.MEDIUM, label: t('project.priority.medium') },
  { value: TaskPriority.HIGH, label: t('project.priority.high') },
  { value: TaskPriority.URGENT, label: t('project.priority.urgent') }
])

const statusOptions = computed(() => [
  { value: TaskStatus.TODO, label: t('project.status.todo') },
  { value: TaskStatus.IN_PROGRESS, label: t('project.status.inProgress') },
  { value: TaskStatus.REVIEW, label: t('project.status.review') },
  { value: TaskStatus.COMPLETED, label: t('project.status.completed') },
  { value: TaskStatus.CANCELLED, label: t('project.status.cancelled') }
])

// 表单验证规则
const rules = computed<FormRules>(() => ({
  title: [
    { required: true, message: t('project.taskTitleRequired'), trigger: 'blur' },
    { min: 2, max: 200, message: t('project.taskTitleLength'), trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: t('project.taskDescriptionLength'), trigger: 'blur' }
  ],
  priority: [
    { required: true, message: t('project.priorityRequired'), trigger: 'change' }
  ],
  estimatedHours: [
    { 
      validator: (rule, value, callback) => {
        if (value !== undefined && (value < 0 || value > 999)) {
          callback(new Error(t('project.estimatedHoursRange')))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  actualHours: [
    { 
      validator: (rule, value, callback) => {
        if (value !== undefined && (value < 0 || value > 999)) {
          callback(new Error(t('project.actualHoursRange')))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}))

// 方法
const disabledDate = (time: Date) => {
  // 不能选择过去的日期（除非任务已经完成）
  if (props.task?.status === 'COMPLETED') return false
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const handleClose = () => {
  dialogVisible.value = false
}

const initForm = () => {
  if (!props.task) return
  
  form.value = {
    title: props.task.title,
    description: props.task.description || '',
    priority: props.task.priority as TaskPriority,
    assigneeId: props.task.assigneeId,
    dueDate: props.task.dueDate,
    estimatedHours: props.task.estimatedHours,
    actualHours: props.task.actualHours,
    status: props.task.status
  }
  
  // 根据状态设置进度
  switch (props.task.status) {
    case 'TODO':
      taskProgress.value = 0
      break
    case 'IN_PROGRESS':
      taskProgress.value = 50
      break
    case 'REVIEW':
      taskProgress.value = 80
      break
    case 'COMPLETED':
      taskProgress.value = 100
      break
    case 'CANCELLED':
      taskProgress.value = 0
      break
    default:
      taskProgress.value = 0
  }
}

const handleSubmit = async () => {
  if (!formRef.value || !props.task) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      // 格式化数据
      const formData = { ...form.value }
      delete formData.status // 状态通过单独的API更新
      
      await taskApi.updateTask(props.task!.id, formData)
      
      // 如果状态有变化，单独更新状态
      if (props.task!.status !== form.value.status) {
        await taskApi.updateTaskStatus(props.task!.id, form.value.status)
      }
      
      ElMessage.success(t('project.updateTaskSuccess'))
      emit('success')
      handleClose()
    } catch (error) {
      console.error('更新任务失败:', error)
      ElMessage.error(t('project.updateTaskError'))
    } finally {
      loading.value = false
    }
  })
}

// 监听任务变化
watch(() => props.task, (newTask) => {
  if (newTask) {
    initForm()
  }
})

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible && props.task) {
    initForm()
  }
})

// 监听进度变化，自动更新状态
watch(taskProgress, (newProgress) => {
  if (newProgress === 0) {
    form.value.status = TaskStatus.TODO
  } else if (newProgress < 50) {
    form.value.status = TaskStatus.TODO
  } else if (newProgress < 80) {
    form.value.status = TaskStatus.IN_PROGRESS
  } else if (newProgress < 100) {
    form.value.status = TaskStatus.REVIEW
  } else {
    form.value.status = TaskStatus.COMPLETED
  }
})
</script>

<style scoped lang="scss">
.w-100 {
  width: 100%;
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-container {
  width: 100%;

  .el-slider {
    margin: 12px 0;
  }

  .progress-info {
    margin-top: 8px;
    text-align: center;
    font-size: 14px;
    color: var(--el-text-color-regular);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
